import * as THREE from '../../../../modules/three/three.module.js'
import {drawCircle, flatten} from "../util/StaticMethods.js";

const circleTexture = new THREE.Texture(drawCircle());
circleTexture.needsUpdate = true;
const color = '#1d1df6';

// 负责渲染从 无人机飞控 获取的 无人机航线
// 目前只适用于 展示历史的无人机航线，不支持实时的
export default class FlyPathIndicator extends THREE.Points {
  /**
   * 数据来自于 AI 的航线规划
   * @type {DroneFlyPath}
   */
  path

  /**
   * 地球直角坐标系坐标 乘以该矩阵 得到世界坐标系坐标
   * @type {THREE.Matrix4}
   */
  earthPosToWorld = new THREE.Matrix4()
  firstPosition = new THREE.Vector3()

  lineMtl = new THREE.LineBasicMaterial({
    color: color,
    toneMapped: false,
    transparent: true,
  })

  pointMtl = new THREE.PointsMaterial( {
    size: 12,
    color: color,
    sizeAttenuation: false,
    map: circleTexture,
    alphaTest: 0.5,
    toneMapped: false,
    transparent: true } )

  constructor(droneFlyPath, toEarthCoordMat) {
    super();
    this.material = this.pointMtl;
    this.path = droneFlyPath;
    this.earthPosToWorld.copy(toEarthCoordMat).invert();
    this._drawPath();
  }

  _drawPath() {
    const coords = this.path.droneCoords.map(it => {
      return new THREE.Vector3(it.x, it.y, it.z).applyMatrix4(this.earthPosToWorld);
    });
    if (coords.length) {
      this.firstPosition.copy(coords[0]);
    }
    this.geometry.setAttribute('position', new THREE.BufferAttribute(flatten(coords), 3));
    const lineGeo = new THREE.BufferGeometry();
    lineGeo.setAttribute('position', new THREE.BufferAttribute(flatten(coords), 3));
    const line3d = new THREE.Line(lineGeo, this.lineMtl);
    this.add(line3d);
    coords.forEach((coord, index) => {
      const facing = this.path.facing[index];
      const frame = new THREE.AxesHelper(1);
      frame.applyQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(1,0,0), facing));
      frame.position.copy(coord);
      // this.add(frame);

      const arrowHelper2 = new THREE.ArrowHelper(facing, coord, 1, color);
      arrowHelper2.setLength(0.3, 0.3 * 0.4, 0.07);
      this.add(arrowHelper2);
      if (index > 0) {
        const pre = coords[index - 1];
        const pos = coord.clone().lerp(pre, 0.5);
        const orient = coord.clone().sub(pre).normalize();
        const arrowHelper = new THREE.ArrowHelper(orient, pos, 1, color);
        arrowHelper.setLength(0.3, 0.3 * 0.4, 0.07);
        this.add(arrowHelper);
      }
    });
  }
}
